/***************************************************************/
/********************* Balance Check Tables ********************/
/***************************************************************/

** IMP: Data/Intermediate/PropOldTeammates.dta (in Switch =  prop_newteammates) and Data/Intermediate/linesection_sharemuslims.dta (in Switch = share_muslim) are generated in this do-file and then are used in Section_Aggregates.do in Prep Folder. But Section_Aggregates.do is also called in the HD_LD_sections swtich in this do-dile.

clear
set more off
set segmentsize 3g
set scheme plotplainblind


* Switches for different tables
local balance_tables        1
local HD_LD_dm              1
local promotion             1
local sec_change_balance    1
local prop_newteammates     1 
local hindu_muslim_balance  1
local share_muslim          1
local attrition             1
local HD_LD_sections        1
local employee_task_h       1
local baseline_sorting		1




*-------------------------------*
*       Balance Tables         *
*-------------------------------*
if `balance_tables' == 1 {
    
    * Load Data
    use "$Data/Final/Balance_check.dta", clear
    
    * Define list of dependent variables and their labels
    local dep_vars "tenure mean_contact_hindu_ls orders_rel comm_rel age school trust ln_donate int_cross"
    local var_labels "Tenure Share_Muslim_co_workers Orders Communication Age School Trust Altruism Inter_religious_contact"
    
    * Initialize counters for observations and means
    forvalues i = 1/9 {
        local obs`i' = .
        local mean`i' = .
        local p`i' = .
    }
    
    * Loop through each dependent variable for regression
    local i = 1
    foreach var of local dep_vars {
        * Determine if the variable is a factor relevant at work or outside
        local factor = ""
        if inlist("`var'", "tenure", "mean_contact_hindu_ls", "orders_rel", "comm_rel") {
            local factor = "at_work"
        }
        else {
            local factor = "outside_work"
        }
        
        * Run regression with fixed effects and cluster
        areg `var' c.mixed#i.direct i.religion, absorb(line_sec) cluster(line_sec_team)
        eststo A`i'
        
        * Store observations, mean, and adjusted R square
        local obs`i' = e(N)
        su `var' if e(sample), meanonly
        local mean`i' = string(round(r(mean), 0.01))
		local r`i' = string(round(e(r2_a), 0.001), "%9.3f")
        
        * Conduct hypothesis test
        test 0.direct_dependency#c.mixed = 1.direct_dependency#c.mixed
        local p`i' = string(round(r(p), 0.01))
        
        local ++i
    }
    
    * Check if all estimations are stored
    eststo dir
    
    * Export main balance table with religion effects
    estout A1 A2 A3 A4 A5 A6 A7 A8 A9 using "$Output/Tables/tables_balance_main.tex", ///
        style(tex) replace ///
        keep(0.direct_dependency#c.mixed 1.direct_dependency#c.mixed) ///
        cells(b(star fmt(%9.4f)) se(par)) ///
        nolabel collabels(none) mlabels(none) ///
        starlevels(* 0.10 ** 0.05 *** 0.01) ///
        varlabels(0.direct_dependency#c.mixed "Mixed $\times$ LD" ///
                  1.direct_dependency#c.mixed "Mixed $\times$ HD")
    
    * Construct LaTeX footnotes
    local tex "\\hline"
    local tex "`tex' p(Mixed $\times$ HD = Mixed $\times$ LD) & `p1' & `p2' & `p3' & `p4' & `p5' & `p6' & `p7' & `p8' & `p9' \\\\"
    local tex "`tex' Observations & `obs1' & `obs2' & `obs3' & `obs4' & `obs5' & `obs6' & `obs7' & `obs8' & `obs9' \\\\"
    local tex "`tex' Mean Dep. Var & `mean1' & `mean2' & `mean3' & `mean4' & `mean5' & `mean6' & `mean7' & `mean8' & `mean9' \\\\"
    local tex "`tex' Religion F.E. & Yes & Yes & Yes & Yes  & Yes & Yes & Yes & Yes & Yes \\\\"
	local tex "`tex' Line $\times$ Section Effects & Yes & Yes & Yes & Yes  & Yes & Yes & Yes & Yes & Yes \\\\"
	local tex "`tex' Adj. $ R^2$ & `r1' & `r2' & `r3' & `r4' & `r5' & `r6' & `r7' & `r8' & `r9' \\\\"
    local tex "`tex' \\multicolumn{9}{p{8cm}}{\\tiny \\textit{Notes:} Standard errors clustered at line-section-team level. Mixed is a dummy variable coded 1 if the line-section-level team is religiously mixed. *** p<0.01, ** p<0.05, * p<0.1.} \\\\ \\end{tabular} }"
    
    * Export detailed balance table
    esttab A1 A2 A3 A4 A5 A6 A7 A8 A9 using "$Output/Tables/tables_rating_balance_maina.tex", ///
        style(tex) replace booktabs ///
        d(*) nolabel collabels(none) noobs ///
        postfoot("`tex'") nonum ///
        mtitles("(1)" "(2)" "(3)" "(4)" "(5)" "(6)" "(7)" "(8)" "(9)") ///
        mgroups("Tenure" "Muslim co-workers" "Orders" "Communication" "Age" "Schooling" "Trust" "Altruism" "Inter-religious contact outside work", ///
                pattern(1 1 1 1 1 1 1 1 1) ///
                prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
    
   *--------------------------------------------*
    * 2. Main Table without Religion Effects    *
    *--------------------------------------------*
    eststo clear
    
    * Reset counters for observations and means
    forvalues i = 1/9 {
        local obs`i' = .
        local mean`i' = .
        local p`i' = .
    }
    
    local i = 1
    foreach var of local dep_vars {
        * Run regression without religion effects
        areg `var' c.mixed#i.direct_dependency, absorb(line_sec) cluster(line_sec_team)
        eststo B`i'
        
        * Store observations, adjusted R squares, and mean
        local obs`i' = e(N)
        quietly summarize `var' if e(sample), meanonly
        local mean`i' = string(round(r(mean), 0.01))
		local r`i' = string(round(e(r2_a), 0.001), "%9.3f")
        
        * Conduct hypothesis test
        test 0.direct_dependency#c.mixed = 1.direct_dependency#c.mixed
        local p`i' = string(round(r(p), 0.01))
        
        local ++i
    }
    
    * Export main balance table without religion effects
    estout B1 B2 B3 B4 B5 B6 B7 B8 B9 using "$Output/Tables/tables_balance_main_no_religion.tex", ///
        style(tex) replace ///
        keep(0.direct_dependency#c.mixed 1.direct_dependency#c.mixed) ///
        cells(b(star fmt(%9.4f)) se(par)) ///
        nolabel collabels(none) mlabels(none) ///
        starlevels(* 0.10 ** 0.05 *** 0.01) ///
        varlabels(0.direct_dependency#c.mixed "Mixed $\times$ LD" ///
                  1.direct_dependency#c.mixed "Mixed $\times$ HD")
    
    * Construct LaTeX footnotes for no religion effects table
    local tex "\\hline"
    local tex "`tex' p(Mixed $\times$ HD = Mixed $\times$ LD)  & `p1' & `p2' & `p3' & `p4' & `p5' & `p6' & `p7' & `p8' & `p9' \\\\"
    local tex "`tex' Observations & `obs1' & `obs2' & `obs3' & `obs4' & `obs5' & `obs6' & `obs7' & `obs8' & `obs9' \\\\"
    local tex "`tex' Mean Dep. Var & `mean1' & `mean2' & `mean3' & `mean4' & `mean5' & `mean6' & `mean7' & `mean8' & `mean9' \\\\"
    local tex "`tex' Line $\times$ Section Effects & Yes & Yes & Yes & Yes  & Yes & Yes & Yes & Yes & Yes  \\\\"
	local tex "`tex' Adj. $ R^2$ & `r1' & `r2' & `r3' & `r4' & `r5' & `r6' & `r7' & `r8' & `r9' \\\\"
    local tex "`tex' \\multicolumn{9}{p{8cm}}{\\tiny \\textit{Notes:} Standard errors clustered at line-section-team level. Mixed is a dummy variable coded 1 if the line-section-level team is religiously mixed. *** p<0.01, ** p<0.05, * p<0.1.} \\\\ \\end{tabular} }"
    
    * Export detailed balance table without religion effects
    esttab B1 B2 B3 B4 B5 B6 B7 B8 B9 using "$Output/Tables/tables_rating_balance_main_no_religiona.tex", ///
        style(tex) replace booktabs ///
        d(*) nolabel collabels(none) noobs ///
        postfoot("`tex'") nonum ///
        mtitles("(1)" "(2)" "(3)" "(4)" "(5)" "(6)" "(7)" "(8)" "(9)") ///
        mgroups("Tenure" "Muslim co-workers" "Orders" "Communication" "Age" "Schooling" "Trust" "Altruism" "Inter-religious contact outside work", ///
                pattern(1 1 1 1 1 1 1 1 1) ///
                prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
    
    *--------------------------------------------*
    * 3. Main Table with Line Effects (HD vs LD) *
    *--------------------------------------------*

    
    * Define list of dependent variables
    local dep_vars_line_effects "tenure mean_contact_hindu_ls orders_rel comm_rel age school trust ln_donate int_cross"
    
    * Initialize counters for observations, means, and p-values
    forvalues i = 1/9 {
        local obs_line`i' = .
        local mean_line`i' = .
        local p_line`i' = .
    }
    
    * Loop through each dependent variable for regression with line effects
    local i = 1
    foreach var of local dep_vars_line_effects {
        * Run regression with fixed effects and cluster
        areg `var' mixed direct c.mixed#c.direct_dependency i.religion, absorb(line_r) cluster(line_sec_team)
        eststo C`i'
        
        * Store observations, R squares and mean
        local obs_line`i' = e(N)
        quietly summarize `var' if e(sample)
        local mean_line`i' = string(round(r(mean), 0.01))
		local r`i' = string(round(e(r2_a), 0.001), "%9.3f")
        
        * Conduct hypothesis test for interaction term
        test c.mixed#c.direct_dependency = 0
        local p_line`i' = string(round(r(p), 0.01))
        
        local ++i
    }
    
    * Export main balance table with line effects
    estout C1 C2 C3 C4 C5 C6 C7 C8 C9 using "$Output/Tables/tables_balance_main_LE.tex", ///
        style(tex) replace ///
        keep(mixed direct_dependency c.mixed#c.direct_dependency) ///
        cells(b(star fmt(%9.4f)) se(par)) ///
        nolabel collabels(none) mlabels(none) ///
        starlevels(* 0.10 ** 0.05 *** 0.01) ///
        varlabels(mixed "Mixed" ///
				  direct_dependency "HD" ///
                  c.mixed#c.direct_dependency "Mixed $\times$ HD")
				  
    * Construct LaTeX footnotes
    local tex_LE "\\hline"
    local tex_LE "`tex_LE' p(Mixed $\times$ HD = 0) & `p_line1' & `p_line2' & `p_line3' & `p_line4' & `p_line5' & `p_line6' & `p_line7' & `p_line8' & `p_line9' \\\\"
    local tex_LE "`tex_LE' Observations & `obs_line1' & `obs_line2' & `obs_line3' & `obs_line4' & `obs_line5' & `obs_line6' & `obs_line7' & `obs_line8' & `obs_line9' \\\\"
    local tex_LE "`tex_LE' Mean Dep. Var & `mean_line1' & `mean_line2' & `mean_line3' & `mean_line4' & `mean_line5' & `mean_line6' & `mean_line7' & `mean_line8' & `mean_line9' \\\\"
	local tex_LE "`tex_LE' Adj. $ R^2$ & `r1' & `r2' & `r3' & `r4' & `r5' & `r6' & `r7' & `r8' & `r9' \\\\"
    local tex_LE "`tex_LE' Line $\times$ Section Effects & Yes & Yes & Yes & Yes  & Yes & Yes & Yes & Yes & Yes \\\\"
    local tex_LE "`tex_LE' \\multicolumn{9}{p{8cm}}{\\tiny \\textit{Notes:} Standard errors clustered at line-section-team level. Mixed is a dummy variable coded 1 if the line-section-level team is religiously mixed. *** p<0.01, ** p<0.05, * p<0.1.} \\\\ \\end{tabular} }"
    
    * Export detailed balance table with line effects
    esttab C1 C2 C3 C4 C5 C6 C7 C8 C9 using "$Output/Tables/tables_rating_balance_main_LEa.tex", ///
        style(tex) replace booktabs ///
        d(*) nolabel collabels(none) noobs ///
        postfoot("`tex_LE'") nonum ///
        mtitles("(1)" "(2)" "(3)" "(4)" "(5)" "(6)" "(7)" "(8)" "(9)") ///
        mgroups("Tenure" "Muslim co-workers" "Orders" "Communication" "Age" "Schooling" "Trust" "Altruism" "Inter-religious contact outside work", ///
                pattern(1 1 1 1 1 1 1 1 1) ///
                prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
    
}


*-------------------------------*
*  Line-Level Mean Differences  *
*-------------------------------*


if `HD_LD_dm' == 1{
	
* Load Data
use "$Data/Final/Balance_check.dta", clear


gen section_changed = section != new_section

* Label for table
la var tenure "Tenure"
la var mean_contact_hindu_ls "Share Muslim co-workers (Hindus)"
la var orders_rel "Taking Orders"
la var comm_rel "Communicating"
la var high_skilled "Semi-skilled/Operator"
la var section_changed "Changed section"
la var age "Age"
la var school "Schooling"
la var trust "Trust"
la var ln_donate "Altruism"
la var int_cross "Inter-religious contact (Outside work)"


* Balance Table
dmout tenure mean_contact_hindu_ls school  orders_rel comm_rel high_skilled ///
section_changed age school trust ln_donate int_cross  using "$Output/Tables/ss_HD_LD_dm", by(HD_mixed) vce(robust) tex replace
		
}	



*-------------------------------*
*         Promotion            *
*-------------------------------*
if `promotion' == 1 {
    
    * Load Data
    use "$Data/Final/Balance_check.dta", clear
    
    * Define list of regression variables and labels
    local reg_vars "high_skilled"
    local reg_labels "Promoted_Semi-skilled_Operator"
    
    * Initialize counters for observations and means
    forvalues i = 1/3 {
        local obs`i' = .
        local mean`i' = .
        local p`i' = .
    }
    
    * Define list of scenarios
    local scenarios "all direct_dependency=1 direct_dependency=0"
    
    * Loop through each regression scenario
    local i = 1
    foreach scenario in `scenarios' {
        if "`scenario'" == "all" {
            regress `reg_vars' school tenure age 2.religion, vce(robust)
        }
        else if ("`: word 1 of `scenario''") == "direct_dependency=1" {
            regress `reg_vars' school tenure age 2.religion if direct_dependency == 1, vce(robust)
        }
        else if ("`: word 1 of `scenario''") == "direct_dependency=0" {
            regress `reg_vars' school tenure age 2.religion if direct_dependency == 0, vce(robust)
        }
        
        eststo A`i'
        
        * Store observations and mean
        local obs`i' = e(N)
        su `reg_vars' if e(sample), meanonly
        local mean`i' = string(round(r(mean), 0.01))
        
        local ++i
    }
    
    * Export promotion table
    estout A1 A2 A3 using "$Output/Tables/table_promotion.tex", ///
        style(tex) replace ///
        keep(school_years tenure age 2.religion) ///
        cells(b(star fmt(%9.4f)) se(par)) ///
        nolabel collabels(none) mlabels(none) ///
        starlevels(* 0.10 ** 0.05 *** 0.01) ///
        varlabels(school_years "School Years" ///
                  tenure "Tenure" ///
                  age "Age" ///
                  2.religion "Muslim")
    
    * Construct LaTeX footnotes
    local tex "\\hline"
    local tex "`tex' Mean Dep. Var & `mean1' & `mean2' & `mean3' \\\\"
    local tex "`tex' Observations & `obs1' & `obs2' & `obs3' \\\\"
    local tex "`tex' \\multicolumn{4}{p{8cm}}{\\tiny \\textit{Notes:} Standard errors clustered at line-section-team level. *** p<0.01, ** p<0.05, * p<0.1.} \\\\ \\end{tabular} }"
    
    * Export detailed promotion table
    esttab A1 A2 A3 using "$Output/Tables/tables_cont_promotiona.tex", ///
        style(tex) replace booktabs ///
        d(*) nolabel collabels(none) noobs ///
        postfoot("`tex'") nonum ///
        mtitles("(1)" "(2)" "(3)") ///
        mgroups("Promoted (Semi-skilled/Operator)", ///
                pattern(1) ///
                prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
}

*-------------------------------*
*    Section Change Balance     *
*-------------------------------*

if  `sec_change_balance' == 1{
	
	* Load Data
    use "$Data/Final/Balance_check.dta", clear
	
	* Fixed effects for line x old section
    egen line_oldsec = group(Line_R section)

	* Dummy if changed section due to randomization
    gen section_change = section != new_section

    /* Regressions Section Change and Treatment Status -- Table A.7 */
    eststo clear
    eststo: areg section_change  c.mixed i.religion, absorb(line_sec) cluster(line_sec_team)
    eststo: areg section_change  c.mixed#i.direct i.religion, absorb(line_sec) cluster(line_sec_team)
esttab using "$Output/Tables/tables_rating_pooled", tex  keep(mixed 1.direct_dependency#c.mixed  0.direct_dependency#c.mixed)  se ar2 starlevels(* 0.10 ** 0.05 *** 0.010) replace
	
}


*------------------------------------*
*   Proporotion of New Teammates     *
*------------------------------------*

if `prop_newteammates' == 1{
	
* Load Data
use "$Data/Final/Balance_check.dta", clear

* Group before randomization
  egen old_group = group(Line section shift)

keep name section shift religion _id new_section strata rand_num ///
     ordering team Line_R direct_dependency mixed old_group
	 
	 preserve
	 
	 foreach var of varlist _all{
	 	rename `var' `var'_2
	 }
	 
	 tempfile balance_check_2
	 
	 save `balance_check_2'
	 
	 restore
	 
	  foreach var of varlist _all{
	 	rename `var' `var'_1
		
	 }
	 
	 cross using `balance_check_2'
	 
	 


    keep if team_1 == team_2 & Line_R_1 == Line_R_2 & new_section_1 == new_section_2

    gen teammate_old = old_group_1 == old_group_2 if !mi(old_group_1, old_group_2)
    gen teammate_old_muslim = old_group_1 == old_group_2 if !mi(old_group_1, old_group_2) &  religion_2 == 2

    keep name_1 name_2 section_1 shift_1 religion_1 _id_1 new_section_1 strata_1 rand_num_1 ordering_1 team_1 Line_R_1 direct_dependency_1 mixed_1  old_group_1 old_group_2 teammate_old teammate_old_muslim


    rename section_1 section
    rename new_section_1 new_section
    rename _id_1 _id
    rename strata_1 strata
    rename rand_num_1 rand_num
    rename ordering_1 ordering
    rename team_1 team 
    rename Line_R_1 Line_R
    rename direct_dependency_1 direct_dependency
    rename mixed_1 mixed
    rename religion_1 religion



   egen line_section = group(Line_R new_section)
   egen line_section_team = group(Line_R new_section team)
   encode Line_R, gen(line_r)
   gen count_w = 1


   collapse (rawsum) count_w (mean) teammate_old teammate_old_muslim mixed direct_dependency line_section line_section_team line_r  religion, by(_id)
drop if !inlist(direct_dependency, 0, 1)


   ** Balance in proportion of old teammates - Table A.6 **
   eststo clear
   eststo: areg teammate_old mixed i.religion, absorb(line_section) cluster(line_section)
   eststo: areg teammate_old c.mixed#i.direct_dependency i.religion, absorb(line_section) cluster(line_section)
   test c.mixed#0.direct_dependency = c.mixed#1.direct_dependency
sum teammate_old [aw = count_w] /* 34% of teammates are known on average */
esttab using "$Output/Tables/tables_propoldteammates", tex keep(mixed  1.direct_dependency#c.mixed  0.direct_dependency#c.mixed )  se ar2 starlevels(* 0.10 ** 0.05 *** 0.010) replace


  replace teammate_old_muslim = . if religion == 2
  keep _id teammate_old_muslim


save "$Data/Original/PropOldTeammates.dta", replace


}


*-----------------------------------------------*
*   Balance in Hindu Muslim Characteristics     *
*-----------------------------------------------*

if `hindu_muslim_balance' == 1{
	
	* Load Data
	 use "$Data/Final/Balance_check.dta", clear
	 
*---------------------------------------------------------------
* 2. Classifying *Baseline* Sections into HD and LD
*---------------------------------------------------------------

* Capitalize the first letter of each word in 'section' for consistency
replace section = proper(section)

* Initialize 'baseline_dependency' to 0 for all observations
gen baseline_dependency = 0 

* Assign 'baseline_dependency' = 1 based on Line and "old section"
replace baseline_dependency = 1 if ///
    section == "Maida" | ///
    (inlist(LN, "Line 3") & inlist(section, "Depanning", "Cfc", "Packing", "1St Line", "2Nd Line")) | ///
    (inlist(LN, "Line 1") & inlist(section, "Deposit", "Cfc", "Packing")) | ///
    (inlist(LN, "Line 2") & inlist(section, "Deposit", "Cfc", "Packing", "Injector")) | ///
    (inlist(LN, "Line 4") & inlist(section, "Cfc", "Packing")) | ///
    (inlist(LN, "Line 5", "Line 6") & inlist(section, "Box Filling", "Cfc", "Box Machine"))

    * Balance Table (Table B.1)
	dmout baseline_dependency school_years tenure int_cross orders_rel comm_rel neighbour_attitude ///
nrc_support  using "$Output/Tables/ss", by(religion) tex replace

	
	
}


*-----------------------------------------------*
*   Balance across HD/LD tasks for Share Muslim    *
*-----------------------------------------------*

if `share_muslim' == 1{
	
* Load Data
use "$Data/Original/Randomized_Teams.dta", clear
    

encode Line_R, gen(line_r)
gen rel = Religion == "Islam"
egen share_m = mean(rel), by(Line_R team new_section)


** collapsing by section **
collapse (firstnm) line_r mixed direct (mean) share_m, by(Line_R team new_section)

** Table A.3 **
eststo clear
eststo: reg share_m direct_dependency i.line_r if mixed, cluster(line_r)
esttab using "$Output/Tables/table_sharem",  keep(direct_dependency) tex se ar2 starlevels(* 0.10 ** 0.05 *** 0.010) replace

** Save dataset with Muslim shares **
keep Line_R new_section team share_m
la var share_m "Share Muslims (post-randomization)"
save "$Data/Original/linesection_sharemuslims.dta", replace

}

*-----------------------------------------------*
****   Check for differential attrition    ******
*-----------------------------------------------*

if `attrition' == 1{

* Load Randomized_Teams
use $Data/Final/Balance_check.dta, clear

* Merge with attrition data
merge 1:1 _id using $Data/Original/attrited.dta, keep(3) nogen /* HR report on attrition */
 

* Table
areg attrited mixed i.religion, absorb(line_sec) robust
eststo A1
local obs1 = e(N)
su attrited if e(sample) == 1
local meanA = string(round(r(mean), .01))

areg attrited c.mixed#i.direct i.religion, absorb(line_sec) robust
eststo A2
local obs2 = e(N)
su attrited if e(sample) == 1
local meanB = string(round(r(mean), .01))
 test 0.direct_dependency#c.mixed = 1.direct_dependency#c.mixed
local p1 = string(round(r(p), .01))

estout A1 A2 using  "$Output/Tables/attrition.tex", style(tex) replace ///
	keep(mixed  0.direct_dependency#c.mixed  1.direct_dependency#c.mixed) ///
	cells(b(star fmt(%9.4f)) se(par)) ///
	nolabel collabels(none) mlabels(none) starlevels(* 0.10 ** 0.05 *** 0.01) ///
	varlabels( mixed "Mixed" ///
				0.direct_dependency#c.mixed  "Mixed X LD" ///
				1.direct_dependency#c.mixed  "Mixed X HD")
				
				
local tex " \\ \hline"
local tex "`tex' Observations & `obs1' & `obs2'  \\"
local tex "`tex'p(Mixed X HD = Mixed X LD) &  & `p1'  \\"
local tex "`tex' Mean Dep. Var & `meanA' & `meanB'  \\"
local tex "`tex' Religion Effects & Yes & Yes  \\"
local tex "`tex' Line*Section Effects & Yes & Yes  \\"
local tex "`tex' \multicolumn{5}{p{8cm}}{\tiny \textit{Notes:} Standard errors clustered at line-section-team level."
local tex "`tex' Mixed  is  a  dummy  variable  coded  1  if  the  line-section-level  team  is  religiously mixed." 
local tex "`tex' *** p<0.01, ** p<0.05, * p<0.1.} \\ \end{tabular} }"
	
esttab A1 A2 using "$Output/Tables/attritiona", style(tex) replace booktabs ///
	d(*) nolabel collabels(none) noobs postfoot("`tex'") nonum ///
	mtitles("(1)" "(2)") ///
	mgroups("Attrited", pattern(1 1) ///
	prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span}))
}	

*-------------------------------------------*
** Org. differences between HD/LD sections **
*-------------------------------------------*

if `HD_LD_sections' == 1{
	
* Load line-section-level
use $Data/Final/linesectionlevel_data.dta, clear


collapse (mean) rating (firstnm) mixed dependency, by(Line_R new_section team)



merge 1:1 Line_R team new_section using $Data/Original/Section_Aggregates.dta

* Replace tenure skilled as missing if 0 (it was changed to 0 for merginig with line_section_level ratings)
replace tenure_skilled = . if tenure_skilled == 0

* Sections without ratings
replace dependency = 1 if Line_R == "MAIDA"
replace dependency = 0 if Line_R == "EGG"


la var mixed "Mixed"
la var dep "HD"

la var count_workers "Team Size"
la var tenure_skilled "Tenure: Skilled Workers"
la var tenure_unskilled "Tenure: Unskilled Workers"
la var age "Age"
la var school_years "Years of schooling"
la var share_m "Share Muslim"
la var high_skilled "Share operator/semi-skilled"
la var high_skilled_hindu "Share operator/semi-skilled (Hindu)"
la var high_skilled_muslim "Share operator/semi-skilled (Muslim)"
la var count_unskilled "Number of unskilled workers"


dmout count_workers tenure_skilled tenure_unskilled ///
age school_years share_m high_skilled high_skilled_hindu high_skilled_muslim count_high_skilled count_unskilled using $Output/Tables/ss_HD_LDsections_dm, by(dependency) tex replace

	
	
}


*-------------------------------------------*
*         Employee task history             *
*-------------------------------------------*

if `employee_task_h' == 1{
	
	* Load Data
	use $Data/Original/employee_task_history.dta, clear
	
	* merge with baseline data
	merge 1:1 _id using $Data/Final/Baseline_Cleaned.dta, keep(3)  ///
	nogen keepusing(school_years tenure age religion skill)
	
	* Line x section group for first job
	egen line_s_f = group(first_line firstjob_section)
	
	/* Analysis: Matrix of Dependency Changes (Table A1) */
    tab dependency_first dependency_last

   /* Check predictors of dependency changes (Table A2) */
    eststo clear
    eststo: areg dependency_switched age tenure school i.religion, absorb(line_s_f) cluster(line_s_f)
    eststo: areg High_Low age tenure school i.religion, absorb(line_s_f) cluster(line_s_f)
    eststo: areg Low_High age tenure school i.religion, absorb(line_s_f) cluster(line_s_f)
	
	esttab using "$Output/Tables/dependency_sorting.tex", ///
    replace ///
    b(4) se(4) star(* 0.10 ** 0.05 *** 0.01) ///
    alignment(D{.}{.}{-3}) ///
    label ///
    mtitles("Switched Dependency" "High to Low" "Low to High") ///
    title("Dependency sorting")
	


	
}



*-------------------------------*
*      Baseline Sorting         *
*-------------------------------*
if `baseline_sorting' == 1 {
	* Load Data
    use "$Data/Final/Balance_check.dta", clear
	
	gen hindu = (religion == 1)
	merge 1:1 _id using "$Data/Original/teamlist_baseline.dta" /* Cohort information during baseline survey from HR */
	
	encode shiftincharge, gen(cohort)
	label define cohortlabel 1 "Cohort 1" 2 "Cohort 2" 3 "Cohort 3"
	label value cohort cohortlabel
	
	label define linelabel 1 "Line 1" 2 "Line2" 3 "Line 3" 4 "Egg" 5 "Line 4" 6 "Line 5" 7 "Flour" 8 "Line 6"
	label value line_r linelabel
	
	reg hindu i.line_r, robust
	coefplot, drop(_cons) order(1.line_r 2.line_r 3.line_r 5.line_r 6.line_r 8.line_r 4.line_r 7.line_r) vertical baselevels ciopts(recast(rcap)) yline(0, lcolor(purple%50))
	graph export "$Output/Figures/Rcom_Lines.pdf", as(pdf) replace
	
	
	reg hindu i.cohort, robust
	coefplot, drop(_cons) order(1.cohort 2.cohort 3.cohort) vertical baselevels ciopts(recast(rcap)) yline(0, lcolor(purple%50))
	graph export "$Output/Figures/Rcom_cohorts.pdf", as(pdf) replace
}


